package com.hctforgreen.greenservice.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.hctforgreen.greenservice.LoginActivity;
import com.hctforgreen.greenservice.R;

import org.json.JSONObject;

public class TokenUtil {
    private static final String TAG = "TokenUtil";
    private static final String STATUS_CODE = "statusCode";

    /**
     * 校验token是否过期
     *
     * @param context
     * @param json
     * @return
     */
    public static String checkToken(Context context, String json) {
        try {
            final Activity activity = (Activity) context;
            if (activity == null) {
                return json;
            }
            JSONObject jsonObject = new JSONObject(json);
            if (jsonObject.has(STATUS_CODE)
                    && jsonObject.getString(STATUS_CODE).equals("102")) {// token非法
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, activity.getString(R.string.login_token_overtime), Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(activity, LoginActivity.class);
                        // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        try {
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);// 4.0以上支持，2.2可能会造成无法完全退出
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        activity.startActivity(intent);
                        activity.finish();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtil.d(TAG, "jsonString = " + json);
        return json;
    }
}
